<?php

namespace app\pay\controller;

use app\api\model\mysql\MallOrder;
use app\api\model\mysql\MallOrderGoods;
use app\api\model\mysql\MallSetting;
use app\api\model\mysql\MallUserPaylog;
use app\BaseController;
use app\common\lib\Sign;
use app\common\lib\Str;
use EasyWeChat\Factory;
use think\facade\Log;

class Notify extends BaseController
{
    /**
     * @return false|void
     */
    public function index(){
        try{
            $app = Factory::payment(config('wechat.pay'));
            $response = $app->handlePaidNotify(function($message, $fail) {
                // 使用通知里的 "微信支付订单号" 或者 "商户订单号" 去自己的数据库找到订单

                $order = (new MallUserPaylog())->getUserPaylogByOrdersn($message['out_trade_no']);
                if (!$order || $order['status']==1) { // 如果订单不存在 或者 订单已经支付过了
                    return true; // 告诉微信，我已经处理完了，订单没找到，别再通知我了
                }
                // 商城订单支付
                if($message['attach'] == 'payshop') {
                    $shoporder = (new MallOrder())->getByOrderIds($order['order_id']);
                    if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态，不代表支付状态
                        // 用户是否支付成功
                        if ($message['result_code'] === 'SUCCESS') {
                            $orderdata = array('paytime' => time(), 'status' => 1);
                            $order->save($orderdata); // 保存订单
                            // 更新商城订单
                            $shoporder->save(array('paytime' => time(), 'orderstatus' => 1));
                            $this->sendprint($order['order_id']);
                        }
                    }
                }else {
                    Log::error("通信失败");
                    return $fail('通信失败，请稍后再通知我');
                }
            });
            $response->send(); // return $response;
        }catch (\Exception $e){
            Log::error("level" . $e->getMessage() . " " . $e->getFile() . "　" . $e->getLine());
            return false;
        }
    }

    /**
     * 打印回调
     * @return void
     */
    public function sendprint($order_id){
        $setting =(new MallSetting())->where("name='isopenid'")->find();
        if($setting && $setting['option_value']==1){
            $row = (new MallOrder())->getByOrderIds($order_id);
            $goodslist =(new MallOrderGoods())->where("order_id",'=',$order_id)->select()->toArray();
            $guid= Str::guid();
            $content = "<FS2><center>**#1 荐贝康**</center></FS2>";
            $content .= str_repeat('.', 32);
            $content .= "<FS2><center>--在线支付--</center></FS2>";
            $content .= "<FS><center>荐贝康小程序商城</center></FS>";
            $content .= "订单时间:". $row['create_time'] . "\n";
            $content .= "订单编号:".$row['ordersn']."\n";
            $content .= str_repeat('*', 14) . "商品" . str_repeat("*", 14);
            $content .= "<table>";
            $content .= "<tr><td>名称</td><td>数量</td><td>单价</td></tr>";
            foreach ($goodslist as $k=>$v){

                $content .= "<tr><td>".$v['goods_name']."</td><td>x".$v['total']."</td><td>".$v['price']."</td></tr>";
            }
            $content .= "</table>";
            $content .= str_repeat('.', 32);
            $content .= "小计:￥".$row['orderprice']."\n";
            $content .= "折扣:￥".$row['discountprice']." \n";
            $content .= str_repeat('*', 32);
            $content .= "订单总价:￥".$row['payprice']." \n";
            $content .= str_repeat('*', 32);
            $content .= "收货人:".$row['realname']." \n";
            $content .= "收货地址:".$row['address']." \n";
            $content .= "收货人电话:".$row['mobile']." \n";
            $content .= "<FS2><center>**#1 完**</center></FS2>";
            $senddata=array(
                'machineCode'=>'4004701676',
                'content'=>$content,
                'type'=>1,
                'id'=>$guid
            );
            Sign::getInstance()->__post($senddata,'print/printer');
        }
        return true;
    }

}